package org.tinygroup.sample;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

@Component
public class StringRequestChanger {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public String changerXml(Message<String> msg) throws Exception {
		logger.infoMessage("changer request xml:[{0}]", msg.getPayload());
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		Document document = dbf.newDocumentBuilder().parse(
				new InputSource(new StringReader(msg.getPayload())));
		Element tageElement = document.createElement("tag");
		Text textNode = document.createTextNode("我是一个段落文本!");
		tageElement.appendChild(textNode);
		document.getDocumentElement().appendChild(tageElement);
		return transform(document.getDocumentElement());
	}

	protected String transform(Element element) throws Exception {
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		transformer.transform(new DOMSource(element), new StreamResult(output));
		return new String(output.toByteArray());
	}
}